import os
import sys

pwd = os.getcwd()
f_pwd = os.path.dirname(pwd)
sys.path.insert(0, f_pwd)

from common.gene_log import Get_Time
from common.My_serial import my_serial
from common.auto import Auto

at = Auto("at").reco_com()
# print(at)
my_serial1 = my_serial(at)

ser = my_serial1.gene_serial()

tcp1 = [hex(i) for i in range(256)]

x = "".join(tcp1)

def tcp_send():
    filename = Get_Time()
    ser.timeout = 3
    ser.write('AT+CIPSTART=TCP,"115.29.164.59",40432\r\n'.encode())
    result = ser.read(500).decode()
    with open("tcp_log/%s.txt" % filename, "a+")as f:
        f.write(Get_Time()+" << \r\n"+result)
    print(result)
    a = 0
    right = 0
    fail = 0
    time_out = 0
    try:
        while True:
            b = "[" + str(a) + "]"
            data = b + x
            atcipsend = "AT+CIPSEND=%d\r\n" % data.__len__()
            ser.timeout = 1
            ser.write(atcipsend.encode())
            print(ser.read(100).decode())
            with open("tcp_log/%s.txt" % filename, "a+")as f:
                f.write(Get_Time()+" << \r\n"+ser.read(100).decode())
            ser.timeout = 8
            ser.write(data.encode())

            return_data = ser.read(99999).decode()
            while True:
                if not return_data:
                    return_data = ser.read(99999).decode()
                    time_out += 1
                    if time_out in [i * 10 for i in range(1, 10000)]:
                        pass
                else:
                    break
            with open("tcp_log/%s.txt" % filename, "a+")as f:
                f.write(Get_Time()+" << \r\n"+return_data)

            rec_data = return_data.split("\r\n")
            print("this is data:%s" % data)
            print("this is rec:%s" % rec_data[2])
            with open("tcp_log/%s.txt" % filename, "a+")as f:
                f.write("this is data:%s" % data)
                f.write("this is rec:%s" % rec_data[2])

            a += 1

            if rec_data[2] == data:
                right += 1

            elif rec_data[2] != data:
                fail += 1
            else:
                pass
            print("当前成功了%d次,失败了%d次,超时了%d次" % (right, fail, time_out))
            with open("tcp_log/%s.txt" % filename, "a+")as f:
                f.write(Get_Time()+" << \r\n"+"当前成功了%d次,失败了%d次,超时了%d次" % (right, fail, time_out))

    except KeyboardInterrupt as e:
        # print("请手动关闭TCP链接[at+cipshut]")
        print("程序关闭！")
    except Exception as e:
        raise e
    finally:
        ser.write("at+cipshut\r\n".encode())
        print(ser.read(10000))
        ser.close()

tcp_send()